package com.ldr.danmuku.item

import android.util.Log
import androidx.core.util.Pools
import com.ldr.danmuku.BuildConfig

/**
 * @author :create by ldr
 * time:2022/12/28 15:47
 * @descript:弹幕库一个个弹幕view的缓存池
 */
class DanMuItemViewPool<V : Any> :Pools.Pool<V> {

    companion object{
        private const val TAG = "DanMu"
      val sPoolSync = Object()
    }
    //缓存池
    private var mPool:ArrayList<V> = ArrayList()

    //池子最大的容量
    var mMaxPoolSize = 50

    //从池子中获取对象
    override fun acquire(): V? {
        synchronized(sPoolSync) {
            if (mPool.size > 0) {
                val index = mPool.size - 1
                return mPool.removeAt(index)
            }
            return null
        }
    }

    //释放并将对象放到池子中
    override fun release(instance: V): Boolean {
       if (isInPool(instance)){
           Log.d(TAG,"对象已经存在池子里面了==此处有问题")
           if (BuildConfig.DEBUG){
               throw IllegalStateException("对象已经存在池子里面了==此处有问题")
           }
           return false
       }
       synchronized(sPoolSync){
          if (mPool.size >= mMaxPoolSize)  return false
          mPool.add(instance)
          return true
       }
    }

    //判断是否在池子里面
    private fun isInPool(instance: V): Boolean {
       return mPool.contains(instance)
    }

}